<?php 
class BannersController extends DomController {
	
	public function index() {
		$this->banners();
	}
	
	public function calendar() {
		
		$post = DomFgPost::getInstance('bannersCalendar')->store('bannersCalendar', array('start','end','location') );
		
		$defaultStart = date('Y-m-d');
		$defaultEnd = date('Y-m-d', strtotime('+30 days'));
		
		$start = new DomDateTime( $post->start ? $post->start : $defaultStart );
		$start = $start->getMonthFirstDay();
		$end = new DomDateTime( $post->end ? $post->end : $defaultEnd );
		$end = $end->getMonthLastDay();
		
		function dayHandler( DomFgCalendarDay $day, DomController $controller, array $locations ) {
			$post = DomFgPost::getInstance();
			
			$banners = BannersQuery::c()
				->onlyForDate( $day->stamp )
				->onlyPublic()
				->orderBy('t.location DESC');
			
			if( $_GET['location'] ) {
				$banners->onlyLocation( $_GET['location'] );
			} else if( $post->location) {
				$banners->onlyLocation( $post->location );
			}
				
			$banners = $banners->commit()->toArray();
			
			static $i;
			
				
			$boxes = '<br style="clear:left" />';
			$prev = '';
			foreach( $banners as $banner ) {
				//if( $post->location == '' ) {
					$current = $locations[$banner->location]['name'];
					if( $current != $prev ) {
						$boxes .= '<center><a href="'.$controller->getUrl('Calendar/&location='.$current).'" style="font-weight:bold; font-size:11px; color:'.$locations[$banner->location]['color'].'">'.$current.'</a></center>';
						$prev = $current;
					}
				//}

				//$i++;
				//$script = '<script type="text/javascript">banner_'.$i.' = "'.addslashes($banner->getBannerHtml('')).'";</script>';
				//$over = 'id="banner_'.$i.'" onmouseover="tip.show(\'banner_'.$i.'\',\''.$banner->name.'\',\'\')"';
				
				$i++;
				$tip = DomFgToolTip::c()->title($banner->name)->contents($banner->getBannerHtml(''))->elementId('banner_'.$i);
				$boxes .= '<a id="banner_'.$i.'" href="'.$controller->getUrl('manageBanner/'.$banner->id).'" style="text-decoration:none; display:block; color:black; background-color:rgb(249,236,236); margin:0 0 1px 0; padding: 2px; font-size:11px;">
					'.$banner->name.'
				</a>';
			}
			$day->style = 'width:100px; min-height:60px;';
			return $boxes;
		}
		
		$panel = array(
			'title' => 'Kalender',
			'layout' => 'table',
			'style' => 'width:800px;',
			'action' => $this->getUrl('calendar/'.$id),
			'layoutConfig' => array(
				'columns' => 4,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				array(
					'title' => 'Algus',
					'type' => 'date',
					'name' => 'start',
					'value' => $post->start ? $post->start : $defaultStart,
				),
				array(
					'title' => 'Lõpp',
					'type' => 'date',
					'name' => 'end',
					'value' => $post->end ? $post->end : $defaultEnd,
				),
				array(
					'title' => 'Asukoht',
					'type' => 'select',
					'values' => arrayMerge(array(''=>array('name'=>'All')),Banner::getLocationsList()),
					'name' => 'location',
					'selected' => $post->location ? $post->location : 'all',
				),
				array(
					'type' => 'button',
					'title' => 'Kuva',
					'colspan' => 2,
				),
				array(
					'type' => 'calendar',
					'start' => $start->date(),
					'end' => $end->date(),
					'monthStyle' => 'border: 1px dotted lightgrey; margin-bottom: 5px; ',
					'dayHandler' => 'dayHandler',
					'dayHandlerArgs' => array($this, Banner::getLocations() ),
					'colspan' => 4,
				),
			),
			'buttons' => array(
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
			),
		);
				
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	public function banners() {
		
		$post = DomFgPost::getInstance('bannersSearch');
		
		$query = Banner::query()->orderBy('name');
		if( $post->doSearch ) {
			$post->store('bannersSearch',array('doSearch','searchWord'));
			$query->where('name LIKE \'%'.$post->searchWord.'%\' OR moderator LIKE \'%'.$post->searchWord.'%\' ');
		}
		$source = new DomArDataSource( $query, 50 );
	
	
	
		$panel = array(
			'title' => 'Kalender',
			'layout' => 'table',
			'style' => 'width:900px;',
			'action' => $this->getUrl('banners'),
			'layoutConfig' => array(
				'columns' => 4,
				'columnWidths' => array( 190,50,100 ),
			),
			'items' => array(
				array(
					'type' => 'button',
					'title' => 'Lisa uus bänner',
					'link' => $this->getUrl('manageBanner/'),
				),
				array(
					'type' => 'textField',
					'title' => 'Otsi',
					'name' => 'searchWord',
					'value' => $post->searchWord,
				),
				array(
					'type' => 'button',
					'name' => 'doSearch',
					'title' => 'Otsi',
				),
				
			),
		);
	
		function getDaysHandler( &$row) {
			return ($row->onWeekDay1 ? 'E' : '' ) . ($row->onWeekDay2 ? 'T' : '' ) . ($row->onWeekDay3 ? 'K' : '' ) . ($row->onWeekDay4 ? 'N' : '' ) . ($row->onWeekDay5 ? 'R' : '' ) . ($row->onWeekDay6 ? 'L' : '' ) . ($row->onWeekDay7 ? 'P' : '' ) . ($row->onPairedDays == 0 ? NULL : ($row->onPairedDays == 1 ? '(1)' : '(2)'));
		}
		
		function bannerName( &$row ) {
			if( $row->description ) 
				return $row->description;
			else
				return $row->banner->name;
		}
		
		function dateHandler( &$row ) {
			$a = $row->start->inPast() ? 1 : 0;
			$b = $row->end->inPast() ? 1 : 0;
			switch( $a+$b ) {
				case 2: $color = 'red'; break;
				case 1: $color = 'green'; break;
				default: $color = 'blue'; break;
			}
			
			return '<span style="color:'.$color.'">'.$row->start->date().' - '.$row->end->date().'</span> ';
		}

		function name( &$banner, $i ) {
			DomFgToolTip::c()->title($banner->name)->contents($banner->getBannerHtml(''))->elementId('banner_'.$i);
			return '<div id="banner_'.$i.'">'.$banner->name.'</div>';
		}
		
		function active( &$row ) {
			return $row->active ? 'Jah' : 'Ei';
		}
		
		$panel['items'][] = $grid = array(
			'type' => 'grid',
			'colspan' => 4,
			'name' => 'times',
			'source' => $source,
			'fields' => array(
				array('title'=>'Nimi', 'handler'=>'name', 'link'=>$this->getUrl('manageBanner/'), 'width'=>250 ),
				array('title'=>'Asukoht', 'key'=>'location','width'=>100 ),
				array('title'=>'Haldur', 'key'=>'moderator' ),
				array('title'=>'Periood', 'handler'=>'dateHandler','width'=>170 ),
				array('title'=>'Päevad', 'handler'=>'getDaysHandler' ),
				array('title'=>'Aktiivne', 'handler'=>'active' ),
				array('type'=>'gridButton','value'=>'Muuda', 'title'=>'Valikud', 'link'=>$this->getUrl('manageBanner/'),'colspan'=>2,'width'=>50 ),
				array('type'=>'gridButton','value'=>'Kustuta', 'key'=>'clicks', 'link'=>$this->getUrl('deleteBanner/'), 'width'=>50, 'confirmMessage' => 'Oled sa kindel, et soovid kustutada?' ),
			),
		);
		
		
		$this->view->contents = DomFg::render( $panel );
	}
	
	public function manageBanner( $id = NULL ) {
		$new = $id == 0;
		$item = $new ? new Banner() : Banner::load($id);
		
		$post = DomFgPost::getInstance();

		if( $post->deleteBannerFile ) {
			$item->banner->unlink();
		}
		
		if( $post->save ) {
			
			$item->name 	= $post->name;
			$item->link 	= $post->link;
			$item->moderator= $post->moderator;
			$item->info 	= $post->info;
				
			$item->banner->addUploaded( $post->banner[0], $post->banner[1] );
			$item->code 	= $post->code;
			
			$item->start 	= $post->start;
			$item->end 		= $post->end;
			$item->active 	= (bool)$post->active;
			$item->location = $post->location;
			
			$item->onWeekDay1 = (bool)$post->on[0];
			$item->onWeekDay2 = (bool)$post->on[1];
			$item->onWeekDay3 = (bool)$post->on[2];
			$item->onWeekDay4 = (bool)$post->on[3];
			$item->onWeekDay5 = (bool)$post->on[4];
			$item->onWeekDay6 = (bool)$post->on[5];
			$item->onWeekDay7 = (bool)$post->on[6];		
				
			$item->onPairedDays = (int)$post->onPairedDays;
			
			if( $item->save() ) {
				$id = $item->id;
				$message = array('message' => 'Salvestatud','type' => 'ok','colspan' => 2,);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'error','colspan' => 2,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}
				
		// ---------------------------------------
		
		$tabPanel = array(
			'type' => 'tabPanel',
			'style' => 'width:800px;',
			'tabsStyle' => 'width:800px;',
			'headerTabs' => true,
			'action' => $this->getUrl('manageBanner/'.$id),
			'items' => array($message),
			'buttons' => array(
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
			),
		);
				
		// ---------------------------------------
				
		$tab1 = array(
			'type' => 'panel',
			'title' => 'Bänner',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				array(
					'title' => 'Üldine',
					'type' => 'fieldSet',
					'colspan' => 4,
					'layoutConfig' => array(
						'columns' => 4,
						'columnWidths' => array(100,255,100),
					),
					'layout' => 'table',
					'items' => array( 
						array(
							'type' => 'textField',
							'title' => 'Nimi',
							'name' => 'name',
							'value' => $item->name,
							'colspan' => 3,
							'style' => 'width: 600px',
						),
						array(
							'type' => 'textField',
							'title' => 'Link',
							'name' => 'link',
							'value' => $item->link,
							'colspan' => 3,
							'style' => 'width: 600px',
						),
						array(
							'type' => 'select',
							'title' => 'Asukoht',
							'name' => 'location',
							'values' => Banner::getLocationsList(),
							'selected' => $item->location,
						),
						array(
							'title' => 'Aktiivne',
							'type' => 'checkBox',
							'name' => 'active',
							'checked' => (bool)$item->active,
						),
					),
				),
				(!$item->banner->exists() ? NULL :
				array(
					'colspan' => 4,
					'type' => 'image',
					'src' => $item->banner->getUrl(),
					'style' => 'height:100px; margin: 0 4px 0 4px;'
				)),
				array(
					'title' => 'Bänner',
					'type' => 'fieldSet',
					'colspan' => 4,
					'layout' => 'table',
					'layoutConfig' => array(
						'columns' => 4,
						'columnWidths' => array(100),
					),
					'items' => array( 
						array(
							'title' => 'Fail',
							'name' => 'banner',
							'type' => 'file',
						),
						array(
							'title' => 'Kood',
							'name' => 'code',
							'type' => 'textArea',
							'value' => $item->code,
							'rowspan' => 3,
						),	
						array('type' => 'value',),
						array(
							'type' => 'button',
							'title' => 'Kustuta bänneri fail',
							'name' => 'deleteBannerFile',
							'colspan' => 2,
						),		
						array('type' => 'value','value'=>''),		
					),
				),
				array(
					'type' => 'fieldSet',
					'title' => 'Ajastamine',
					'colspan' => 4,
					'layout' => 'table',
					'layoutConfig' => array(
						'columns' => 4,
					),
					'items' => array( 
						array(
							'title' => 'Algus',
							'type' => 'date',
							'name' => 'start',
							'value' => $item->start->date(),
						),
						array(
							'title' => 'Lõpp',
							'type' => 'date',
							'name' => 'end',
							'value' => $item->end->date(),
						),
						array(
							'title' => 'Päevad',
							'type' => 'checkBoxGroup',
							'name' => 'on',
							'vertical' => true,
							'checked' => array($item->onWeekDay1,$item->onWeekDay2,$item->onWeekDay3,$item->onWeekDay4,$item->onWeekDay5,$item->onWeekDay6,$item->onWeekDay7),
							'values' => array('E','T','K','N','R','L','P'),
						),
						array(
							'title' => 'Päevad',
							'type' => 'radioGroup',
							'name' => 'onPairedDays',
							'checked' => (int)$item->onPairedDays,
							'values' => array(0 => 'Mõlemad', 2 => 'Paaris', 1 => 'Paaritud'),
						),
					),
				),
				array(
					'title' => 'Lisa info',
					'type' => 'fieldSet',
					'colspan' => 4,
					'layoutConfig' => array(
						'columns' => 2,
						'columnWidths' => array(100),
					),
					'layout' => 'table',
					'items' => array( 
						array(
							'title' => 'Haldur',
							'name' => 'moderator',
							'type' => 'textField',
							'value' => $item->moderator,
						),
						array(
							'title' => 'Info',
							'name' => 'info',
							'type' => 'textArea',
							'style' => 'width: 529px; height: 70px',
							'value' => $item->info,
							'colspan' => 4,
						),
					),
				),
			),
		);
		$tabPanel['items'][] = &$tab1;
		
		
		
		
		
		// ---------------------------------------
		list($dayList,$dayMax) = $item->getDayStatistics( 33 );
		$daySource = new DomFgDataSource( $dayList ,100 );
		
		list($hourList,$hourMax) = $item->getHourStatistics();
		$hourSource = new DomFgDataSource( $hourList ,100 );
		
		list($dayOfWeekList,$dayOfWeekMax) = $item->getDayOfWeekStatistics();
		$dayOfWeekSource = new DomFgDataSource( $dayOfWeekList ,100 );
		
		function bar( &$row, $i, $max ) {
			return '<div style="height:6px; background-color: blue; width: '.(int)(($row['clicks']*200/$max)).'px"></div>';
		}
		
		$tab2 = array(
			'type' => 'panel',
			'title' => 'Statistika',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 400 ),
			),
			'items' => array(
				array(
					'type' => 'value',
					'title' => '<b>Klikke kokku</b>',
					'value' => DomSql::selectOneQuery('SELECT count(*) as n FROM '.Banner::STATISTICS_TABLE_NAME.' WHERE banner = '.(int)$item->id.'','n'),
				),
				array(
					'rowspan' => 3,
					'type' => 'grid',
					'source' => $daySource,
					'fields' => array(
						array('key' => 'date', 'title' => 'Kuupäev', 'width'=>120,),
						array('key' => 'clicks', 'title' => 'Klikke', 'colspan'=>2),
						array('handler'=>'bar', 'handlerArgs' => array( $dayMax ), 'title' => 'Klikke'),
					),
				),
				array(
					'colspan' => 2,
					'type' => 'grid',
					'source' => $dayOfWeekSource,
					'fields' => array(
						array('key' => 'day', 'title' => 'Tund', 'width'=>100,),
						array('key' => 'clicks', 'title' => 'Klikke', 'colspan'=>2),
						array('handler'=>'bar', 'handlerArgs' => array( $dayOfWeekMax ), 'title' => 'Klikke'),
					),
				),
				array(
					'colspan' => 2,
					'type' => 'grid',
					'source' => $hourSource,
					'fields' => array(
						array('key' => 'hour', 'title' => 'Tund', 'width'=>60,),
						array('key' => 'clicks', 'title' => 'Klikke', 'colspan'=>2),
						array('handler'=>'bar', 'handlerArgs' => array( $hourMax ), 'title' => 'Klikke'),
					),
				),
				array(
					'type' => 'value',
					//'value' => '<div style="width:100px;height:500px;"></div>'
				),
			),
		);
		$tabPanel['items'][] = &$tab2;
		
		// ---------------------------------------
				
		$this->view->contents = DomFg::render( $tabPanel );
		
	}
	
	public function setup() {
		//$this->auth('banners');
		
		$menu = array(
			'type' => 'menu',
			'items' => array(
				array(
					'title' => 'Kalender',	
					'link' => $this->getUrl('calendar/'),
				),
				array(
					'title' => 'Bännerid',	
					'link' => $this->getUrl('banners/'),
				),
				array(
					'title' => 'Lisa bänner',	
					'link' => $this->getUrl('managebanner/'),
				),
			),
		);
		$this->view->menu = DomFg::render( $menu );
	}

}
?>